﻿using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using Newtonsoft.Json;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.OmiApi.Log.Entitys;
using RuoVea.OmiApi.Log.Service;
using RuoVea.OmiApi.Log.Service.Dto;
using RuoVea.OmiLog.Attributes;
using RuoVea.OmiLog.Dto;
using RuoVea.OmiLog.Language;
using SqlSugar;
using System.ComponentModel;

namespace RuoVea.OmiLog.Controllers;

/// <summary>
/// 操作日志
/// </summary>
[AppRoute]
public class LogOpController : Controller
{
    private readonly SysLogOpService _thisService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisService"></param>
    public LogOpController(SysLogOpService thisService ) { 
        _thisService = thisService;
    }

    /// <summary>
    /// 参数配置页面
    /// </summary>
    [HttpGet("index")]
    public IActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpPost("pages")]
    public async Task<RestfulResult<PageResult<SysLogOpDto>>> GetPagesAsync()
    {
        RestfulResult<PageResult<SysLogOpDto>> restful = new() { Code = CodeStatus.OK };
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new Exception(i18n.no_upload_data);
        SysLogOpPageParam data = JsonConvert.DeserializeObject<SysLogOpPageParam>(dataStr);
        data ??= new SysLogOpPageParam { PageNo = 1, PageSize = 10 };
        restful.Data = await _thisService.GetPagesAsync(data);
        return restful;
    }

    /// <summary>
    /// 清空操作日志 🔖
    /// </summary>
    /// <returns></returns>
    [HttpDelete]
    [DisplayName("清空操作日志")]
    public RestfulResult Clear()
    {
        RestfulResult restful = new() { Code = CodeStatus.OK, Data = true, };
        _thisService.Clear();
        return restful;
    }

    /// <summary>
    /// 按时间范围删除操作日志
    /// </summary>
    [HttpDelete("clear-by-time")]
    [DisplayName("按时间范围删除操作日志")]
    public async Task<RestfulResult> ClearByTimeRange([FromQuery] DateTime? beginTime, [FromQuery] DateTime? endTime)
    {
        RestfulResult restful = new() { Code = CodeStatus.OK, Data = true, };
        restful.Code = await _thisService.ClearByTimeRange(beginTime, endTime) > 0 ? CodeStatus.OK : CodeStatus.BadRequest;
        return restful;
    }

    /// <summary>
    /// 批量删除操作日志
    /// </summary>
    [HttpPost("batch-delete")]
    [DisplayName("批量删除操作日志")]
    public async Task<RestfulResult> BatchDelete([FromBody] List<long> ids)
    {
        RestfulResult restful = new() { Code = CodeStatus.OK, Data = true, };
        restful.Code = await _thisService.BatchDelete(ids)? CodeStatus.OK : CodeStatus.BadRequest;
        return restful;
    }
}
